// org/example/demo/SqlExecutionResultInspection.java
package org.example.batch;

import com.intellij.codeInspection.*;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.XmlElementVisitor;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlToken;
import com.intellij.psi.xml.XmlTokenType;
import org.example.demo.CheckAllSqlsInFileAction;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class SqlExecutionResultInspection extends LocalInspectionTool {

    @Override
    public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
        return new XmlElementVisitor() {
            @Override
            public void visitXmlTag(XmlTag tag) {
                if (!"sql".equals(tag.getName())) {
                    return;
                }

                SqlCheckResult result = SqlExecutionCache.getResult(tag);
                if (result == null || result.result == null) {
                    return;
                }

                boolean success = result.result.success;
                String message = success ? "SQL 执行成功" : "SQL 执行失败: " + (result.result.message != null ? result.result.message : "未知错误");
                Icon icon = success ? AllIcons.General.InspectionsOK : AllIcons.General.Error;

                // 找到 <sql> 标签内的文本内容元素（用于高亮）
                PsiElement highlightElement = findSqlTextElement(tag);
                if (highlightElement == null) {
                    highlightElement = tag; // fallback
                }

                holder.registerProblem(
                    highlightElement,
                    message,
                    ProblemHighlightType.INFORMATION,
                        new SqlResultGutterIconFix(success) // ← 第四个参数：LocalQuickFix
                );
            }

            // 辅助方法：定位到 SQL 文本内容（避免高亮整个标签）
            private PsiElement findSqlTextElement(XmlTag tag) {
                for (PsiElement child : tag.getChildren()) {
                    if (child instanceof XmlToken) {
                        XmlToken token = (XmlToken) child;
                        if (token.getTokenType() == XmlTokenType.XML_DATA_CHARACTERS) {
                            return token;
                        }
                    }
                }
                return null;
            }
        };
    }
}